package com.jt.service;
import com.jt.dao.MenuMapper;
import com.jt.pojo.Menu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Duration;

@Service
public class MenuServiceImpl implements MenuService{
    @Autowired
    private MenuMapper menuMapper;

   // @Autowired
   // private RedisTemplate redisTemplate;

    @Resource(name="redisTemplate")
    private ValueOperations valueOperations;//从spring.io官方的data项目中去查这种注入方式
    /**
     * 基于id查询菜单信息,要求:
     * 1)先查redis,redis没有去查mysql
     * 2)将从mysql查询到的数据存储到redis
     * @param id
     * @return
     */
    @Override
    public Menu selectById(Long id) {
        //ValueOperations valueOperations = redisTemplate.opsForValue();
        Object obj=valueOperations.get(String.valueOf(id));
        if(obj!=null){
            System.out.println("Get Data from redis");
            return (Menu)obj;
        }
        Menu menu=menuMapper.selectById(id);
        valueOperations.set(String.valueOf(id), menu, Duration.ofSeconds(120));
        return menu;
    }
    @Override
    public Menu insertMenu(Menu menu) {
        menuMapper.insert(menu);
       // ValueOperations valueOperations = redisTemplate.opsForValue();
        valueOperations.set(String.valueOf(menu.getId()), menu, Duration.ofSeconds(120));
        return menu;
    }
    @Override
    public Menu updateMenu(Menu menu) {
        menuMapper.updateById(menu);
       // ValueOperations valueOperations = redisTemplate.opsForValue();
        valueOperations.set(String.valueOf(menu.getId()), menu, Duration.ofSeconds(120));
        return menu;
    }
}
